<template>

  <el-card class="box-card">
    <div class="table-header">
      <div>

        <el-row>
                <el-input
                  style="width: 200px"
                  v-model="urlParams.search"
                  placeholder="请输入名称或主机名或IP"
                  @keyup.enter="onSearch"
                  clearable
                  @clear="onSearch"
                  class="search"
                />
             <!--选择IDC，自动渲染数据-->
              &nbsp&nbsp
              <el-select filterable v-model="urlParams.idc" class="m-2" @click="getIdc" clearable placeholder="请选择机房名称" style="width: 150px">
                <el-option v-for="row in idc" :key="row.id" :label="row.name" :value="row.id" @click="onSearch">
                </el-option>
              </el-select>
            <!--选择分组，自动渲染数据-->
              &nbsp&nbsp
              <el-select filterable v-model="urlParams.server_group" class="m-2" @click="getServerGroup" clearable placeholder="请选择分组名称" style="width: 150px">
                <el-option v-for="row in serverGroup" :key="row.id" :label="row.name" :value="row.id" @click="onSearch">
                </el-option>
              </el-select>
             <el-button type="primary" style="margin-left: 10px" @click="onSearch"><el-icon><search /></el-icon>查询</el-button>
             <el-button type="primary" style="margin-left: 10px" @click="SearchReset"><el-icon><RefreshRight /></el-icon>重置</el-button>
        </el-row>

      </div>
      <div>
          <!--新建连接-->
        <el-button type="primary" style="margin-right: 10px" @click="createTerminal = true"><el-icon><Connection /></el-icon>新建终端</el-button>
        <!--新建主机-->
        <el-dropdown style="margin-right: 10px" >
          <el-button type="primary" >
            <el-icon><plus /></el-icon>&nbsp;新增<el-icon class="el-icon--right"><arrow-down /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="createDialogVisible = true"><el-icon color="#409EFC" :size="20"><OfficeBuilding /></el-icon>物理机或虚拟机</el-dropdown-item>
              <el-dropdown-item @click="excelDialogVisible = true"><el-icon color="#409EFC" :size="20"><DocumentAdd /></el-icon>Excel导入</el-dropdown-item>
              <el-dropdown-item @click="cloudDialogVisible = true"><el-icon color="#409EFC" :size="20"><MostlyCloudy /></el-icon>云主机</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>

        <!--展示列弹出框-->
        <el-popover placement="left" :width="100" v-model:visible="columnVisible" trigger="contextmenu">
          <template #reference>
            <el-button type="primary" @click="columnVisible = true"><el-icon><setting /></el-icon>&nbsp;展示列</el-button>
          </template>
              <div class="colum" style="height: 300px; overflow-x:hidden;">

              <el-checkbox v-model="showColumn.name">名称</el-checkbox>
              <el-checkbox v-model="showColumn.hostname">主机名</el-checkbox>
              <el-checkbox v-model="showColumn.idc">IDC机房</el-checkbox>
              <el-checkbox v-model="showColumn.server_group">主机分组</el-checkbox>
              <el-checkbox v-model="showColumn.machine_type">机器类型</el-checkbox>
              <el-checkbox v-model="showColumn.os_version">系统版本</el-checkbox>
              <el-checkbox v-model="showColumn.public_ip">公网IP</el-checkbox>
              <el-checkbox v-model="showColumn.private_ip">私有IP</el-checkbox>
              <el-checkbox v-model="showColumn.cpu_num">CPU数量</el-checkbox>
              <el-checkbox v-model="showColumn.cpu_model">CPU型号</el-checkbox>
              <el-checkbox v-model="showColumn.memory">内存</el-checkbox>
              <el-checkbox v-model="showColumn.disk">硬盘</el-checkbox>
              <el-checkbox v-model="showColumn.put_shelves_date">上架日期</el-checkbox>
              <el-checkbox v-model="showColumn.off_shelves_date">下架日期</el-checkbox>
              <el-checkbox v-model="showColumn.expire_datetime">租约过期时间</el-checkbox>
              <el-checkbox v-model="showColumn.is_verified">SSH验证状态</el-checkbox>
              <el-checkbox v-model="showColumn.note">备注</el-checkbox>
              <el-checkbox v-model="showColumn.update_time">更新时间</el-checkbox>
              <el-checkbox v-model="showColumn.create_time">创建时间</el-checkbox>

              </div>
            <div style="text-align: right; margin: 0">
              <el-button size="small" type="Default" @click="columnVisible = false">取消</el-button>
              <el-button size="small" type="primary" @click="saveColumn">确认</el-button>
            </div>
        </el-popover>
      </div>
    </div>

    <!--数据表格-->
    <el-table
            :data="tableData"
            style="width: 100%"
            stripe
            :header-cell-style="{background: '#F8F8F8',textAlign: 'center' }"
            v-loading="loading"
            :show-overflow-tooltip="true"
            @cell-dblclick="dbclick"
            height="390px"
            :row-style="{height: '0'}"
            :cell-style="{padding: '4.7px',textAlign: 'center'}"
    >
      <template #empty>
           <el-empty description="暂无数据" />
      </template>
      <el-table-column prop="name" label="名称" width="150px"  v-if="showColumn.name"/>
      <el-table-column prop="hostname" label="主机名" width="150px"  v-if="showColumn.hostname"/>
      <el-table-column prop="idc" label="IDC机房" width="150px"  v-if="showColumn.idc">
          <template #default="scope">
            <img src="../../../assets/img/aliyun.png" style="width: 18px;height: 18px; position: absolute; margin-top: 3px" v-if="scope.row.idc.provider === '阿里云'">
            <img src="../../../assets/img/tencent.png" style="width: 18px;height: 18px; position: absolute; margin-top: 3px" v-else-if="scope.row.idc.provider === '腾讯云'">
            <el-icon :size="18"  color="#409EFC"  style="width: 18px;height: 18px; position: absolute; margin-top: 3px" v-else><office-building/></el-icon>
              <span style="margin-left: 23px;">{{scope.row.idc.city}}-{{scope.row.idc.name}}</span>
          </template>
      </el-table-column>
      <el-table-column prop="server_group" label="主机分组" width="170px"   v-if="showColumn.server_group">
          <template #default="scope">
              <el-tag type="info" v-for="group in scope.row.server_group" :key="group.id">{{group.name}}</el-tag>
          </template>
      </el-table-column>
      <el-table-column prop="machine_type" label="机器类型" width="150px"  v-if="showColumn.machine_type">
          <template #default="scope">
              <span v-if="scope.row.machine_type === 'vm'">虚拟机</span>
              <span v-else-if="scope.row.machine_type === 'cloud_vm'">云主机</span>
              <span v-else>物理机</span>
          </template>
      </el-table-column>
      <el-table-column prop="os_version" label="系统版本" width="150px"  :show-overflow-tooltip="true" v-if="showColumn.os_version"/>
      <el-table-column prop="public_ip" label="公网IP" width="170px"  v-if="showColumn.public_ip">
          <template #default="scope">
              <el-tag  type="info" v-for="(ip, index) in scope.row.public_ip" :key="index">{{ip}}</el-tag>
          </template>
      </el-table-column>
      <el-table-column prop="private_ip" label="私有IP" width="150px"  v-if="showColumn.private_ip">
          <template #default="scope">
              <el-tag type="info" v-for="(ip, index) in scope.row.private_ip" :key="index">{{ip}}</el-tag>
          </template>
      </el-table-column>
      <el-table-column prop="cpu_num" label="CPU"  v-if="showColumn.cpu_num"/>
      <el-table-column prop="cpu_model" label="CPU型号" width="150px"  v-if="showColumn.cpu_model"/>
      <el-table-column prop="memory" label="内存"   v-if="showColumn.memory"/>
      <el-table-column prop="disk" label="硬盘" width="240px"   v-if="showColumn.disk">
          <template #default="scope">
              <el-tag type="info" v-for="(disk, index) in scope.row.disk" :key="index">
                  设备:{{disk.device}}
                  类型:{{disk.type}}
                  容量:{{disk.size}}
              </el-tag>
          </template>
      </el-table-column>
      <el-table-column prop="put_shelves_date" label="上架日期" width="150px" sortable v-if="showColumn.put_shelves_date"/>
      <el-table-column prop="off_shelves_date" label="下架日期" width="150px" sortable v-if="showColumn.off_shelves_date"/>
      <el-table-column prop="expire_datetime" label="过期时间" width="165px" sortable v-if="showColumn.expire_datetime"/>
      <el-table-column prop="is_verified" label="SSH状态" width="110px"  v-if="showColumn.is_verified">
          <template #default="scope">
              <el-tag type="success" v-if="scope.row.is_verified === 'verified'">已验证</el-tag>
              <el-tag type="warning" v-else-if="scope.row.is_verified === 'unverified'">未验证</el-tag>
          </template>
      </el-table-column>
      <el-table-column prop="note" label="备注" width="150px"  v-if="showColumn.note"/>
      <el-table-column prop="update_time" label="更新时间" width="165px" sortable v-if="showColumn.update_time"/>
      <el-table-column prop="create_time" label="创建时间" width="165px" sortable v-if="showColumn.create_time"/>

      <!--操作栏-->
      <el-table-column fixed="right" label="操作" width="320px">
        <template #default="scope">
          <el-button type="primary" plain size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-popconfirm
            title="是否确定删除"
            @confirm="handleDel(scope.$index, scope.row)"
          >
            <template #reference>
              <el-button type="danger" plain size="small" >删除</el-button>
            </template>
          </el-popconfirm>
          <el-button  type="info" plain size="small" @click="handleDesc(scope.$index, scope.row)">详情</el-button>
          <el-button  type="warning" plain size="small" @click="handleSync(scope.$index, scope.row)">同步</el-button>
          <el-button  type="success" plain size="small" @click="terminal(scope.$index, scope.row)">终端</el-button>
        </template>
      </el-table-column>

    </el-table>

    <!--分页-->
    <div style="margin-top: 20px">
      <el-pagination
        v-model:currentPage="currentPage"
        :page-sizes="[10, 20, 30, 40, 50]"
        :page-size="pageSize"
        layout="->, total, sizes, prev, pager, next, jumper"
        :total="total"
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      >
      </el-pagination>
    </div>
  </el-card>

  <ServerEdit v-model:visible="editDialogVisible" :row="row"></ServerEdit>
  <ServerCreate v-model:visible="createDialogVisible"></ServerCreate>
  <ServerCreateExcel v-model:visible="excelDialogVisible"></ServerCreateExcel>
  <ServerCreateCloud v-model:visible="cloudDialogVisible"></ServerCreateCloud>
  <ServerDescribe v-model:visible="descDialogVisible" :row="row"></ServerDescribe>
  <ServerSync v-model:visible="credentialVisible" :row="row"></ServerSync>
  <Terminal v-model:visible="terminallVisible" :row="row"></Terminal>
  <TerminalCreate v-model:visible="createTerminal"></TerminalCreate>
</template>

<script>
    import ServerEdit from "./ServerEdit.vue";
    import ServerCreate from "./ServerCreate.vue";
    import ServerCreateExcel from "./ServerCreateExcel.vue";
    import ServerCreateCloud from "./ServerCreateCloud.vue";
    import ServerDescribe from "./ServerDescribe.vue";
    import ServerSync from "./ServerSync.vue";
    import Terminal from "./Terminal.vue";
    import TerminalCreate from "./TerminalCreate.vue";
    export default {
        data() {
          return {
            loading: false,
            tableData: [],
            total: 0,  // 总数据条数
            pageSize: 10, // 默认每页的数据条数
            currentPage: 1,  // 默认开始页码
            urlParams: {  // URL查询参数
              page_num: 1,
              page_size: 10,
              search: '',
              idc: '',
              server_group: ''
            },
            editDialogVisible: false,
            descDialogVisible: false,
            credentialVisible: false,
            terminallVisible: false,
            createTerminal: false,
            row: '',
            createDialogVisible: false,
            showColumn: {
                name: true,
                hostname: true,
                idc: true,
                server_group: true,
                machine_type: true,
                os_version: true,
                public_ip: true,
                private_ip: true,
                cpu_num: true,
                cpu_model: true,
                memory: true,
                disk: true,
                put_shelves_date: true,
                off_shelves_date: true,
                expire_datetime: true,
                is_verified: true,
                update_time: true,
                create_time: true,
                note: true
            },
            columnVisible: false, // 展示与隐藏
            excelDialogVisible: false,
            cloudDialogVisible: false,
            idc: '',
            serverGroup: '',
          }
        },
        mounted() {
          this.getData();
          // 从浏览器本地存储获取历史展示列
          const columnSet = localStorage.getItem(this.$route.path + '-columnSet');
          // 如果本地有存储则使用
          if(columnSet) {
            this.showColumn = JSON.parse(columnSet)
          }
        },
        methods: {
          getData() {
              // 处理URL查询参数
              if(!this.urlParams.search) {
                  delete this.urlParams.search;
              }
              if(!this.urlParams.idc) {
                  delete this.urlParams.idc;
              }
              if(!this.urlParams.server_group) {
                  delete this.urlParams.server_group;
              }
            this.loading = true;
            this.$http.get('/cmdb/server/', {params: this.urlParams})
              .then(res => {
                // console.log(res.data);
                this.tableData = res.data.data;
                this.total = res.data.count;
                this.loading = false;
              })
          },
           // 分页：监听【选择每页数量】的事件
          handleSizeChange(pageSize) {
              // console.log(pageSize)
              this.pageSize = pageSize; // 重新设置分页显示
              this.urlParams.page_size = pageSize;  // 将最新值设置到数据里，用于下面用新值重新获取数据
              this.getData()
          },
          // 分页：监听【点击页码】的事件
          handleCurrentChange(currentPage) {
              // console.log(currentPage)
              this.currentPage = currentPage; // 重新设置分页显示
              this.urlParams.page_num = currentPage;
              this.getData()
          },
          handleEdit(index, row) {
            // console.log(index,row);
            this.editDialogVisible = true;
            this.row = row;
          },
          handleSync(index, row) {
            //如果主机有凭据直接同步
              if(row.credential) {
                this.$message.success('触发同步中...');
                this.loading = true
                this.$http.get('/cmdb/host_collect/', {params: {'hostname': row.hostname}})
                .then(res => {
                  if (res.data.code === 200) {
                    this.$message.success('同步成功');
                    this.loading = false
                    this.getData();
                  }else {
                    this.loading = false
                  }

                })
              } else {   //如果没有凭据弹窗请选择凭据
                this.credentialVisible = true;
                this.row = row;
              }
          },
          handleDesc(index, row) {
            // console.log(index,row);
            this.descDialogVisible = true;
            this.row = row;
          },
          terminal(index, row) {
            // console.log(index,row);
            this.row = row;
            if (!this.row.credential){
                this.$message.error('获取SSH凭据失败，请更新凭据')
            }else {
                this.terminallVisible = true;
            }
          },
          dbclick(row, column, cell, event){
            this.descDialogVisible = true;
            this.row = row;
          },
          handleDel(index, row) {
              this.$http.delete('/cmdb/server/'+ row.id + '/')
                  .then(res => {
                    if(res.data.code === 200) {
                      this.$message.success('删除成功');
                      this.tableData.splice(index, 1); // 根据表格索引临时删除数据
                    } else {
                      this.$message.error(res.data.msg);
                    }
                  })
                .catch(() => {
                  // this.$message.info('取消');
                })
          },
          onSearch() {
            this.getData();
          },
          SearchReset() {
            this.urlParams.search = '';
            this.urlParams.idc = '';
            this.urlParams.server_group = '';
            this.getData();
          },
          saveColumn() {
            localStorage.setItem(this.$route.path + '-columnSet', JSON.stringify(this.showColumn));
            this.columnVisible = false;
          },
            getIdc() {
              console.log(this.$http.instance);
                this.$http.get('/cmdb/idc/?page_size=50')
                    .then(res => {
                        this.idc = res.data.data;
                    })
            },
            getServerGroup() {
                this.$http.get('/cmdb/server_group/?page_size=50')
                    .then(res => {
                        this.serverGroup = res.data.data;
                    });
            },
        },
        components: {
          ServerDescribe,
          ServerEdit,
          ServerCreate,
          ServerCreateExcel,
          ServerCreateCloud,
          ServerSync,
          Terminal,
          TerminalCreate,
        }
    }
</script>

<style scoped>
  .table-header {
    display: flex;
    margin-bottom: 18px;
    justify-content: space-between;
  }
</style>